import { Component, OnInit, ElementRef, Renderer2 } from '@angular/core';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
// import { Http } from "@angular/http";
import 'rxjs/add/operator/toPromise';
import { Router } from '@angular/router';
import { AuthService } from '../core/service/auth/auth.service';
import { HttpClient } from '@angular/common/http';


@Component({
	selector: 'app-login',
	templateUrl: './login.component.html',
	styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
	userName = '';
	userPassword = '';
	nameNull = false;
	nameError = false;
	passwordNull = false;
	passwordError = false;
	token: string;
	constructor(private http: HttpClient, public auth: AuthService, private router: Router, private elRef: ElementRef, private render: Renderer2, ) { }
	/**
	 * @description 登录函数
	 */
	login() {
		if (!this.userName || !this.userPassword) {
			return;
		}
		const params = {
			username: this.userName,
			password: this.userPassword
		};
		this.http.post(window.API_ROOT + 'api/users/login', params).subscribe((res: any) => {
			if (res.error_code) {
				alert(res.msg);
			} else {
				localStorage.setItem('token', res.data.token);
				this.router.navigate(['main/prescriptions/prescriptions-folder'], {
					queryParams: {
						infoMessage: 'advance'
					}
				});
			}
		});
		// this.router.navigate(['main']);
	}
	ngOnInit() {
		// this.token = localStorage.getItem('token');
		// if (this.token) {
		// 	this.router.navigate(['main/patient/list']);
		// 	return;
		// }
		if (localStorage.getItem('userName')) {
			this.userName = localStorage.getItem('userName');
		}
		if (localStorage.getItem('password')) {
			this.userPassword = localStorage.getItem('password');
		}
		// this.auth.getUser().then(() => {

		// }).catch(() => { });

	}
}
